package cn.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.pojo.Detail;
import cn.pojo.Sort;
import cn.service.DetailService;
import cn.service.SortService;
import cn.util.Page;

@Controller
@RequestMapping("/Detail")
public class DetailController {
	@Resource
	private DetailService detailService;

	@Resource
	private SortService sortService;

	@RequestMapping("/getDetails")
	private String getDetails(@RequestParam(value = "sortId", defaultValue = "0", required = false) Long sortId, //
			@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum, //
			HttpServletRequest request, //
			HttpServletResponse response, //
			Model md) {
		Page<Detail> page = new Page<Detail>();
		page.init(detailService.totalCount(sortId), pageNum);
		System.out.println("-------------------------------------------------" + detailService.totalCount(sortId));
		List<Detail> list = detailService.getDetails(sortId, page.getRowNum(), Page.pageCount);
		for (int i = 0; i < list.size(); i++) {
			list.get(i).setSort(sortService.getSortBySortId(list.get(i).getSortId()));
		}
		page.setList(list);
		// System.out.println(list);
		md.addAttribute("PAGE", page);
		md.addAttribute("SORTID", sortId);
		md.addAttribute("LIST", list);
		return "goodsList";

	}

	@RequestMapping("/toShopping")
	private String toShopping(@RequestParam(value = "id", defaultValue = "0", required = false) Long id, //
			@RequestParam(value = "sortId", defaultValue = "0", required = false) Long sortId, //
			HttpServletRequest request, //
			HttpServletResponse response, //
			Model md) {
		try {
			Detail detail = detailService.getDetailById(id);
			Sort sort = sortService.getSortBySortId(sortId);
			md.addAttribute("DETAIL", detail);
			md.addAttribute("SORT", sort);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "shopping";

	}

	@RequestMapping("/updateShopping")
	private String updateShopping(@RequestParam(value = "id", defaultValue = "0", required = false) Long id, //
			@RequestParam(value = "remaining", defaultValue = "0", required = false) Integer remaining, //
			@RequestParam(value = "shopNum", defaultValue = "0", required = false) Integer shopNum, //
			HttpServletRequest request, //
			HttpServletResponse response, //
			Model md) {
		try {
			int num = detailService.updateDetailById(id, remaining - shopNum);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/Detail/getDetails";

	}

}
